﻿using Module_Debug.Hardware;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Module_Debug
{
    //List<string> lines;
    public partial class VTDR5120 : Form
    {
        //De_Mura ,lines = new List<string>();
        List<string> lines;
        private bool Listening = false;//是否没有执行完invoke相关操作   
        private bool IClosing = false;//是否正在关闭串口，执行Application.DoEvents，并阻止再次invoke  
        //==============ca310===============
        private double auto_lum;//
        private double auto_x;
        private double auto_y;

        /// <summary>
        /// /auto gamma add 20181031
        /// </summary>
        private int flag1 = 1;
        private int flag2 = 1;
        private int flag3 = 1;

        private uint step_l = 1;
        //==============ca310===============

        //private int CAS200_Measure_Gray = 255;
        //private int CAS200_Measure_Count = 0;
        private int CA200_Measure_CE = 0;
        private List<byte> buffer = new List<byte>(2048);//默认分配1/16页内存，并始终限制不允许超过   
        private byte[] Rec_tmp = new byte[1];//
        private byte[] Rec_tmp1 = new byte[1];//
        private byte[] Send_buf = new byte[1];
        private byte signal_mode;
        private byte start_trans_flag = 0;
        private byte continueflag = 0;

        public byte Seil_port_Find_flag = 0;
        private byte[] Driver_IC = new byte[1];
        private List<string> ImageType;
        private delegate void MonitorSerialPortChangeEventHandler();

        CRC16 CRCData = new CRC16();

        frmMain MainForm = null;
        public VTDR5120(frmMain Frm)
        {
            MainForm = Frm;
            InitializeComponent();
            //MainForm.comPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort1_DataReceived);
            string[] s = { ".bmp" };
            this.ImageType = new List<string>(s);
        }

        private void Frm_Activated(object sender, EventArgs e)
        {
            if (CA_Sel.SelectedIndex != 0 && CA_Sel.SelectedIndex != 1)
            {
                CA_Sel.SelectedIndex = 1;
            }
        }
        private void VTDR5120_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            btnBack_Click(btnBack, e);
        }
        private void btnBack_MouseEnter(object sender, EventArgs e)
        {
            ToolTip p = new ToolTip();
            p.ShowAlways = true;
            p.SetToolTip(this.btnBack, "返回屏体初始化设定界面");
        }
        private void btnBack_Click(object sender, EventArgs e)
        {
            MainForm.comPort.DataReceived -= new SerialDataReceivedEventHandler(SerialPort1_DataReceived);//移除本窗口串口处理函数
            MainForm.comPort.DataReceived += new SerialDataReceivedEventHandler(MainForm.SerialPort1_DataReceived);//
            MainForm.Show();
            this.Hide();
        }
        private void VTDR5120_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Visible == true) //子窗体已开启标识
            {
                // MainForm.comPort.Close();
                Thread.Sleep(5);
                MainForm.comPort.DataReceived -= new SerialDataReceivedEventHandler(MainForm.SerialPort1_DataReceived);
                Thread.Sleep(5);
                MainForm.comPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort1_DataReceived);
                Thread.Sleep(5);
                //MainForm.comPort.Open();
                textBox1.Text += "com 已经连接！\r\n";
            }
            else
            {

            }
        }

        private void btnCleanTextBox1_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
        }

        //=================================Timer====Start=========================
        private void T1_Tick(object sender, EventArgs e)
        {
            T1.Enabled = false;
            textBox1.Text = textBox1.Text + "通讯故障!\r\n";
            textBox1.Focus();//获取焦点
            textBox1.Select(textBox1.TextLength, 0);//光标定位到文本最后
            textBox1.ScrollToCaret();//滚动到光标处
        }
        private void T2_Tick(object sender, EventArgs e)
        {

            toolStripStatusLabel2.Text = DateTime.Now.ToString();
        }
        //=================================Timer====end=========================
        bool ReceivOKFlag = false;
        private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)//Getting data from Comm Port
        {
            //if (MainForm.IClosing) return;
            try
            {
                Listening = true;//设置标记，说明我已经开始处理数据，一会儿要使用系统UI的。         
                int n = MainForm.comPort.BytesToRead;
                byte[] buf = new byte[n];

                MainForm.comPort.Read(buf, 0, n);//读取缓冲数据     
                bool data_1_catched = false;//缓存记录数据是否捕获到    
                buffer.AddRange(buf);
                byte CRCH, CRCL;
                if (buffer.Count > 3)
                {
                    if (buffer[0] == 0xFE)
                    {
                        Rec_tmp = new byte[buffer[2] + 5];
                        byte[] crcTemp = new byte[buffer[2] + 5];
                        buffer.CopyTo(0, crcTemp, 0, buffer[2] + 5);

                        CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                        if (buffer[buffer[2] + 5 - 2] != CRCH && buffer[buffer[2] + 5 - 1] != CRCL)     //CRC校验出错
                        {
                            buffer.RemoveRange(0, buffer.Count);
                        }
                        else
                        {
                            buffer.CopyTo(0, Rec_tmp, 0, buffer[2] + 5);//复制一条完整数据到具体的数据缓存   
                            data_1_catched = true;
                            buffer.RemoveRange(0, buffer[2] + 5);//正确分析一条数据，从缓存中移除数据。
                            if (Rec_tmp[4] == 0)
                                continueflag = 1;
                        }
                    }
                    //RECEIVE
                    // 0x0A: 模组Timing参数 设置  返回
                    // 0x0D: 模组的SSD2828配置数据、DriverIC初始化数据  设置  返回
                    // 0x08: RM67120的Gamma读写、寄存器读写、OTP读写    设置  返回
                    // 0x09: RM67195的Gamma读写、寄存器读写、OTP读写    设置  返回
                    // 0x19: RM67295的Gamma读写、寄存器读写、OTP读写    设置  返回
                    // 0x29: RM67198的Gamma读写、寄存器读写、OTP读写    设置  返回
                    // 0x2E: RM67198的Gamma读写、寄存器读写、OTP读写    设置  返回
                    // 0x0E: RM67160的Gamma读写、寄存器读写、OTP读写    设置  返回
                    // 0x1E: RM67162的Gamma读写、寄存器读写、OTP读写    设置  返回
                    // 0x2A: NT37710的Gamma读写、寄存器读写、OTP读写    设置  返回
                    // 0x2b: HX37710的Gamma读写、寄存器读写、OTP读写    设置  返回
                    // 0x2C: RM69300的Gamma读写、寄存器读写、OTP读写    设置  返回
                    // 0x2D: ICN9608的Gamma读写、寄存器读写、OTP读写    设置  返回
                    // 0x30: R66455 的Gamma读写、寄存器读写、OTP读写    设置  返回
                    // 0x31: TC1100 的Gamma读写、寄存器读写、OTP读写    设置  返回
                    // 0x2F: Demura操作    设置  返回
                    // 0x3C: RM69350的Gamma读写、寄存器读写、OTP读写    设置  返回
                    // 0x4A: CH13721的Gamma读写、寄存器读写、OTP读写    设置  返回
                    // 0x4C: UD61720的Gamma读写、寄存器读写、OTP读写    设置  返回
                    // 0x4D: VTDR6110/5120的Gamma读写、寄存器读写、OTP读写    设置  返回
                    else if (((buffer[0] == 0x1E) || (buffer[0] == 0x0E) || (buffer[0] == 0x0D) || (buffer[0] == 0x0A) || (buffer[0] == 0x09) || (buffer[0] == 0x08) || (buffer[0] == 0x19) || (buffer[0] == 0x29) || (buffer[0] == 0x2A) || (buffer[0] == 0x09) || (buffer[0] == 0x2E) || (buffer[0] == 0x2B) || (buffer[0] == 0x2C) || (buffer[0] == 0x2D) || (buffer[0] == 0x2F) || (buffer[0] == 0x30) || (buffer[0] == 0x31) || (buffer[0] == 0x3C) || (buffer[0] == 0x3D) || (buffer[0] == 0x4A) || (buffer[0] == 0x4C) || (buffer[0] == 0x4D)) && (Setting.TempRecord.cmdLen > 0))
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, Setting.TempRecord.cmdLen);//正确分析一条数据，从缓存中移除数据。 
                            }
                        }
                    }
                    else
                        buffer.RemoveRange(0, buffer.Count);
                }
                if (data_1_catched)
                {
                    this.Invoke((EventHandler)(delegate
                    {
                        T1.Enabled = false; //停止超时计数
                        //------------------------------------------------------------------------------------------------------------------------
                        if (Rec_tmp[0] == 0x0A) //LCD配置
                        {
                            switch (Rec_tmp[1])
                            {

                                case 0x01:
                                    switch (Rec_tmp[3])
                                    {
                                        case 0x00: textBox1.Text = textBox1.Text + "LCD配置-通讯OK！\r\n"; break;
                                        case 0x01: textBox1.Text = textBox1.Text + "LCD配置-CRC错误！\r\n"; break;
                                        default: textBox1.Text = textBox1.Text + "LCD配置-未知错误！\r\n"; break;
                                    }
                                    break;
                                case 0x11:
                                    switch (Rec_tmp[3])
                                    {
                                        case 0x00: textBox1.Text = textBox1.Text + "开窗配置-通讯OK！\r\n"; break;
                                        case 0x01: textBox1.Text = textBox1.Text + "开窗配置-CRC错误！\r\n"; break;
                                        default: textBox1.Text = textBox1.Text + "开窗配置-未知错误！\r\n"; break;
                                    }
                                    break;
                                case 0x12:
                                    switch (Rec_tmp[3])
                                    {
                                        case 0x00: textBox1.Text = textBox1.Text + "LCD模式切换-通讯OK！\r\n"; break;
                                        case 0x01: textBox1.Text = textBox1.Text + "LCD模式切换-CRC错误！\r\n"; break;
                                        default: textBox1.Text = textBox1.Text + "LCD模式切换-未知错误！\r\n"; break;
                                    }
                                    break;

                                case 0x07:
                                    switch (Rec_tmp[3])
                                    {
                                        case 0x00:
                                            {
                                                textBox1.Text = textBox1.Text + "颜色-通讯OK！\r\n";
                                                textBox1.Focus();//获取焦点
                                                textBox1.Select(textBox1.TextLength, 0);//光标定位到文本最后
                                                textBox1.ScrollToCaret();//滚动到光标处
                                                ReceivOKFlag = true;
                                            }
                                            break;
                                        case 0x01: textBox1.Text = textBox1.Text + "颜色-CRC错误！\r\n"; break;
                                        default: textBox1.Text = textBox1.Text + "颜色-未知错误！\r\n"; break;
                                    }
                                    break;
                                case 0x17:
                                    {
                                        textBox1.Text = textBox1.Text + "逻辑图-通讯OK！\r\n"; break;
                                    };
                                case 0x08:
                                    {
                                        numPatternR.Value = Decimal.Parse(Rec_tmp[4].ToString());
                                        numPatternG.Value = Decimal.Parse(Rec_tmp[5].ToString());
                                        numPatternB.Value = Decimal.Parse(Rec_tmp[6].ToString());
                                        textBox1.Text = textBox1.Text + "颜色读取-通讯OK！\r\n";
                                    }
                                    break;
                                case 0x03:
                                    {
                                        textBox1.Text = textBox1.Text + "BMP载入完成\r\n";
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        else if (Rec_tmp[0] == 0x4D)      //VTDR6100
                        {
                            string tmp = "";
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            textBox1.Text = textBox1.Text + "写寄存器\tOK！\r\n";
                                    }
                                    break;
                                case 0x02:
                                    {
                                        //if (Setting.TempRecord.VTDR6100CmdType == 0x02)  //register read
                                        {
                                            //string tmp = "";
                                            for (int i = 3; i < (Setting.TempRecord.cmdLen - 3); i++)
                                            {
                                                tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]) + ",";
                                            }
                                            tmp = tmp + String.Format("{0:X2}", Rec_tmp[Setting.TempRecord.cmdLen - 3]);
                                            VTDR6100_txtRegData.Text = tmp;
                                            textBox1.Text = textBox1.Text + "寄存器\t读 OK！\r\n";
                                        }
                                    }
                                    break;
                                case 0x08:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            textBox1.Text = textBox1.Text + "GAMMA \t写 OK！\r\n";
                                        else if (Rec_tmp[4] == 0x02)
                                            textBox1.Text = textBox1.Text + "GAMMA \t写 ERROR！\r\n";
                                    }
                                    break;
                                case 0x07:
                                    {

                                    }
                                    break;
                                case 0x09:
                                    {
                                        if (Setting.TempRecord.VTDR6100CmdType == 0x03)
                                        {

                                            //VTDR6100_R255.Value = Decimal.Parse((Rec_tmp[52] & 0x03).ToString()) * 256 + Decimal.Parse(Rec_tmp[53].ToString());

                                            textBox1.Text = textBox1.Text + "红 Gamma数据\t读 OK！\r\n";
                                        }

                                        else if (Setting.TempRecord.VTDR6100CmdType == 0x04)
                                        {

                                            //VTDR6100_G255.Value = Decimal.Parse((Rec_tmp[52] & 0x03).ToString()) * 256 + Decimal.Parse(Rec_tmp[53].ToString());
                                            textBox1.Text = textBox1.Text + "绿 Gamma数据\t读 OK！\r\n";
                                        }

                                        else if (Setting.TempRecord.VTDR6100CmdType == 0x05)
                                        {

                                            //VTDR6100_B255.Value = Decimal.Parse((Rec_tmp[52] & 0x03).ToString()) * 256 + Decimal.Parse(Rec_tmp[53].ToString());

                                            textBox1.Text = textBox1.Text + "蓝 Gamma数据\t读 OK！\r\n";
                                        }
                                    }
                                    break;

                                case 0x11:
                                    {
                                        switch (Rec_tmp[3])
                                        {
                                            case 0x01:
                                            case 0x02:
                                            case 0x03:
                                                {
                                                    textBox1.Text = textBox1.Text + "Gamma切换成功！\r\n";
                                                }
                                                break;
                                            default: break;
                                        }
                                        /*if (Rec_tmp[4] == 0x00)
                                        {
                                            textBox1.Text = textBox1.Text + "Gamma切换成功！\r\n";
                                        }*/
                                    }
                                    break;

                                case 0x0D:
                                    {
                                        if (Rec_tmp[3] == 0x00)
                                            textBox1.Text = textBox1.Text + "OTP Gamma \t写 OK！\r\n";
                                        else if (Rec_tmp[3] == 0x02)
                                            textBox1.Text = textBox1.Text + "OTP Gamma \t写 ERROR！\r\n";
                                    }
                                    break;

                                case 0x0E:
                                    {
                                        if (Rec_tmp[3] == 0x00)
                                            textBox1.Text = textBox1.Text + "OTP ALL \t写 OK！\r\n";
                                        else if (Rec_tmp[3] == 0x02)
                                            textBox1.Text = textBox1.Text + "OTP ALL \t写 ERROR！\r\n";
                                    }
                                    break;

                                case 0x0F:
                                    {
                                        if (Rec_tmp[3] == 0x00)
                                            textBox1.Text = textBox1.Text + "OTP Page 0 \t写 OK！\r\n";
                                        else if (Rec_tmp[3] == 0x02)
                                            textBox1.Text = textBox1.Text + "OTP Page 0 \t写 ERROR！\r\n";
                                    }
                                    break;

                                case 0x1A:
                                    {
                                        if (Rec_tmp[3] == 0x00)
                                            textBox1.Text = textBox1.Text + "OTP Page 4 \t写 OK！\r\n";
                                        else if (Rec_tmp[3] == 0x02)
                                            textBox1.Text = textBox1.Text + "OTP Page 4 \t写 ERROR！\r\n";
                                    }
                                    break;

                                case 0x1B:
                                    {
                                        if (Rec_tmp[3] == 0x00)
                                            textBox1.Text = textBox1.Text + "OTP Page 1 \t写 OK！\r\n";
                                        else if (Rec_tmp[3] == 0x02)
                                            textBox1.Text = textBox1.Text + "OTP Page 1 \t写 ERROR！\r\n";
                                    }
                                    break;

                                case 0x1C:
                                    {
                                        if (Rec_tmp[3] == 0x00)
                                            textBox1.Text = textBox1.Text + "OTP Page 2 \t写 OK！\r\n";
                                        else if (Rec_tmp[3] == 0x02)
                                            textBox1.Text = textBox1.Text + "OTP Page 2 \t写 ERROR！\r\n";
                                    }
                                    break;

                                case 0x1D:
                                    {
                                        if (Rec_tmp[3] == 0x00)
                                            textBox1.Text = textBox1.Text + "OTP Page 5 \t写 OK！\r\n";
                                        else if (Rec_tmp[3] == 0x02)
                                            textBox1.Text = textBox1.Text + "OTP Page 5 \t写 ERROR！\r\n";
                                    }
                                    break;

                                case 0x1E:
                                    {
                                        if (Rec_tmp[3] == 0x00)
                                            textBox1.Text = textBox1.Text + "OTP Page 7 \t写 OK！\r\n";
                                        else if (Rec_tmp[3] == 0x02)
                                            textBox1.Text = textBox1.Text + "OTP Page 7 \t写 ERROR！\r\n";
                                    }
                                    break;

                                case 0x1F:
                                    {
                                        if (Rec_tmp[3] == 0x00)
                                            textBox1.Text = textBox1.Text + "Write 2810 \t写 OK！\r\n";
                                        else if (Rec_tmp[3] == 0x02)
                                            textBox1.Text = textBox1.Text + "Write 2810 \t写 ERROR！\r\n";
                                    }
                                    break;

                                case 0x0A:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            textBox1.Text = textBox1.Text + "GAMMA \t传输 OK！\r\n";
                                        else if (Rec_tmp[4] == 0x02)
                                            textBox1.Text = textBox1.Text + "GAMMA \t传输 ERROR！\r\n";
                                    }
                                    break;
                                case 0x20:
                                    {
                                        //if (Setting.TempRecord.VTDR6100CmdType == 0x02)  //register read
                                        {

                                            for (int i = 3; i < (Setting.TempRecord.cmdLen - 3); i++)
                                            {
                                                tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]) + ",";
                                            }
                                            tmp = tmp + String.Format("{0:X2}", Rec_tmp[Setting.TempRecord.cmdLen - 3]);
                                            textBox1.Text = textBox1.Text + "\n flash ID \r\n" + tmp + "\n flash \t读 完成！\r\n";
                                            //textBox1.Text = "\r\n flash ID\r\n" + textBox1.Text + "\r\n 寄存器\t读 OK！\r\n";
                                        }
                                    }
                                    break;
                                case 0x21:
                                    textBox1.Text = textBox1.Text + "flash 擦除 完成！\r\n";
                                    break;
                                case 0x22:
                                    if ((Rec_tmp[3] == 0x02) && (Rec_tmp[4] == 0x02))
                                    {
                                        textBox1.Text = textBox1.Text + "Flash_enable OK！\r\n";
                                    }
                                    else
                                    {
                                        textBox1.Text = textBox1.Text + "Flash_enable Fail！\r\n";
                                    }
                                    break;
                                case 0x23:
                                    //Setting.TempRecord.cmdLen = 13;////CRC 特殊处理
                                    for (int i = 3; i < (Setting.TempRecord.cmdLen - 3); i++)
                                    {
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]) + ",";
                                    }
                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[Setting.TempRecord.cmdLen - 3]);
                                    textBox1.Text = textBox1.Text + tmp + "\n ";

                                    textBox1.Text = textBox1.Text + "Check_Flash 完成！\r\n";
                                    break;
                                case 0x24:
                                    textBox1.Text = textBox1.Text + "\n Step_Five 完成！\r\n";
                                    break;
                                case 0x25:
                                    textBox1.Text = textBox1.Text + "Write_Flash 完成！\r\n";
                                    break;
                                case 0x26:
                                    //Setting.TempRecord.cmdLen = 15;////CRC 特殊处理
                                    for (int i = 3; i < (Setting.TempRecord.cmdLen - 3); i++)
                                    {
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]) + ",";
                                    }
                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[Setting.TempRecord.cmdLen - 3]);
                                    textBox1.Text = textBox1.Text + tmp + "\n ";

                                    textBox1.Text = textBox1.Text + "Check_Flash 完成！\r\n";
                                    break;
                                default: break;

                            }
                        }
                        ////---------------------------------------------------Demura----------------------------------------
                        else if (Rec_tmp[0] == 0x2F)  //Demura
                        {
                            if ((Rec_tmp[7] == 0x2E) || (Rec_tmp[7] == 0x3C))   // 297/298/299  //350
                            {
                                if (Rec_tmp[7] == 0x2E)// 297/298/299
                                {
                                    textBox1.Text = textBox1.Text + "297 298 299\r\n";
                                }
                                else if (Rec_tmp[7] == 0x3C) //350
                                {
                                    textBox1.Text = textBox1.Text + "350\r\n";
                                }
                                switch (Rec_tmp[1])
                                {
                                    case 0x01:
                                        {
                                            textBox1.Text = textBox1.Text + "Demura RAM Enable\r\n";
                                        }
                                        break;
                                    case 0x02:
                                        {
                                            textBox1.Text = textBox1.Text + "Demura RAM Disable\r\n";
                                        }
                                        break;
                                    case 0x03:
                                        {
                                            if (Rec_tmp[7] == 0x2E)// 297/298/299
                                            {
                                                if (Rec_tmp[4] == 0x80)
                                                {
                                                    textBox1.Text = textBox1.Text + "Demura RAM write Flash complete ! \r\n";
                                                }
                                            }
                                            else if (Rec_tmp[7] == 0x3C) ///350
                                            {
                                                if (Rec_tmp[4] == 0x08)
                                                {
                                                    textBox1.Text = textBox1.Text + "Demura RAM write Flash1 complete ! \r\n";
                                                }
                                                else if (Rec_tmp[4] == 0x00)
                                                {
                                                    textBox1.Text = textBox1.Text + "ERROR: write Flash1 timeout ! \r\n";
                                                }
                                            }
                                        }
                                        break;
                                    case 0x0A:///350 only
                                        {
                                            if (Rec_tmp[7] == 0x3C) ///350
                                            {
                                                if (Rec_tmp[4] == 0x08)
                                                {
                                                    textBox1.Text = textBox1.Text + "Demura RAM write Flash2 complete ! \r\n";
                                                    MessageBox.Show("载入完成！");
                                                }
                                                else if (Rec_tmp[4] == 0x00)
                                                {
                                                    textBox1.Text = textBox1.Text + "ERROR: write Flash2 timeout ! \r\n";
                                                }
                                            }
                                        }
                                        break;
                                    case 0x04:
                                        {
                                            textBox1.Text = textBox1.Text + "Checksum: " + Rec_tmp[4].ToString("x") + "," + Rec_tmp[5].ToString("x") + "\r\n";
                                        }
                                        break;
                                    case 0x05:
                                        {
                                            if (Rec_tmp[7] == 0x2E)// 297/298/299
                                            {
                                                if (Rec_tmp[4] == 0x80)
                                                {
                                                    textBox1.Text = textBox1.Text + "Flash Erase Success ! \r\n";
                                                }
                                            }
                                            else if (Rec_tmp[7] == 0x3C) ///350
                                            {
                                                if (Rec_tmp[4] == 0x08)
                                                {
                                                    textBox1.Text = textBox1.Text + "Flash Erase Success ! \r\n";
                                                }
                                            }
                                        }
                                        break;
                                    case 0x06:
                                        {
                                            textBox1.Text = textBox1.Text + "flash ID: " + Rec_tmp[4].ToString("x") + "," + Rec_tmp[5].ToString("x") + "," + Rec_tmp[6].ToString("x") + "\r\n";
                                        }
                                        break;
                                    case 0x07:
                                        {
                                            textBox1.Text = textBox1.Text + "Demura function on \r\n";
                                        }
                                        break;
                                    case 0x08:
                                        {
                                            textBox1.Text = textBox1.Text + "Demura function off \r\n";
                                        }
                                        break;
                                    case 0x09:
                                        {
                                            textBox1.Text = textBox1.Text + "Demura OTP complete$ \r\n";
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                        textBox1.Focus();//获取焦点
                        textBox1.Select(textBox1.TextLength, 0);//光标定位到文本最后
                        textBox1.ScrollToCaret();//滚动到光标处
                        if (textBox1.Lines.Length > 200) textBox1.Text = "";
                    }));
                }
            }
            finally
            {
                Listening = false;
            }

        }

        #region   //=================================LCD cfg function:OLED_Show_Click====Start=================
        private void Pattern_Write(byte R_value, byte G_value, byte B_value)
        {
            numPatternR.Value = R_value;
            numPatternG.Value = G_value;
            numPatternB.Value = B_value;
            OLED_Show_Click(btnPatternW, null);
        }
        private void OLED_Show_Click(object sender, EventArgs e)
        {
            Send_buf = new byte[25];
            Button btnTmp = (Button)sender;
            Setting.TempRecord.cmdLen = 25;

            Send_buf[0] = 0x0A; //LCD配置标志
            Send_buf[2] = 0x15; //数据长度
            switch (btnTmp.Name)
            {

                case "btnPatternW":                             //写入Pattern参数
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = byte.Parse(numPatternR.Value.ToString());
                        Send_buf[4] = byte.Parse(numPatternG.Value.ToString());
                        Send_buf[5] = byte.Parse(numPatternB.Value.ToString());
                    }
                    break;
                case "btnred":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0xFF;
                        Send_buf[4] = 0;
                        Send_buf[5] = 0;
                    }
                    break; //R
                case "btngreen":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0;
                        Send_buf[4] = 0xFF;
                        Send_buf[5] = 0;
                    }
                    break; //G
                case "btnblue":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0;
                        Send_buf[4] = 0;
                        Send_buf[5] = 0xFF;
                    }
                    break; //B
                case "btnwhite":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0xFF;
                        Send_buf[4] = 0xFF;
                        Send_buf[5] = 0xFF;
                    }
                    break; //W
                case "btnblack":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0;
                        Send_buf[4] = 0;
                        Send_buf[5] = 0;
                    }
                    break; //BL
                default:
                    break;
            }

            CRCData.CalculateCrc16(Send_buf, out Send_buf[23], out Send_buf[24]);
            try
            {
                MainForm.comPort.Write(Send_buf, 0, 25);
            }
            catch
            {
                MessageBox.Show("OLED_Show串口有误，请检查", "错误");
            }
            //Thread.Sleep(800);
        }
        private void numPatternR_ValueChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                numPatternG.Value = numPatternR.Value;
                numPatternB.Value = numPatternG.Value;
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                numPatternG.Value = numPatternR.Value;
                numPatternB.Value = numPatternG.Value;
            }
        }
        private void checkBox1_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                numPatternG.Enabled = false;
                numPatternB.Enabled = false;
            }
            else
            {
                numPatternG.Enabled = true;
                numPatternB.Enabled = true;
            }
        }
        #endregion //=================================LCD cfg function: OLED_Show_Click====end=================     
        private void CAS200_Measure_Information(double Dgv_lum, double Dgv_x, double Dgv_y)
        {
            int Row_Accum = 0, Current_Index = 0, Row_flag = 0;

            DataGridViewRow Row1 = new DataGridViewRow();
            Row_Accum = this.CAS200_dataGridView.Rows.Count - 1;
            if (Row_Accum != 0)
            {
                Current_Index = this.CAS200_dataGridView.SelectedCells[0].RowIndex;
                if ((Current_Index != Row_Accum - 1) && (Current_Index != Row_Accum))
                {
                    Row_Accum = Current_Index;
                    Row_flag = 1;
                }
                else
                {
                    this.CAS200_dataGridView.Rows.Add(Row1);
                }
                if ((Row_Accum != 0) && (Row_flag != 1))
                {
                    if (Current_Index != Row_Accum)
                    {
                        this.CAS200_dataGridView.Rows[Row_Accum - 1].Selected = false;
                        this.CAS200_dataGridView.Rows[Row_Accum].Selected = true;
                    }
                }
            }
            else
            {
                this.CAS200_dataGridView.Rows.Add(Row1);
            }
            this.CAS200_dataGridView.Rows[Row_Accum].Cells[0].Value = Row_Accum + 1;//序号
            //Rows[x]为第x行,Cells[x]为第x列
            this.CAS200_dataGridView.Rows[Row_Accum].Cells[1].Value = Dgv_x.ToString("#0.0000");
            this.CAS200_dataGridView.Rows[Row_Accum].Cells[2].Value = Dgv_y.ToString("#0.0000");
            this.CAS200_dataGridView.Rows[Row_Accum].Cells[3].Value = Dgv_lum.ToString("#0.0000");
            if (Row_flag == 1)
            {
                Row_flag = 0;
                Row_Accum = this.CAS200_dataGridView.Rows.Count - 1;
                this.CAS200_dataGridView.Rows[Current_Index].Selected = false;
                this.CAS200_dataGridView.Rows[Row_Accum - 1].Selected = true;
            }
            CAS200_dataGridView.FirstDisplayedScrollingRowIndex = CAS200_dataGridView.RowCount - 1;
        }

        #region //--------------------------亮度量测----
        private int CAS200_Measure_Gray = 255;
        private int CAS200_Measure_Count = 0;
        private void T3_Tick(object sender, EventArgs e)  //自动读取亮度
        {

            if (cbx_follow_gamma_points.Checked == true)  //follow gamma绑点
            {
                T3.Enabled = false;
                //if (Point_692AX[0] == 255)
                {
                    numPatternB.Value = numPatternG.Value = numPatternR.Value = Point_VTDR5120[24 - CAS200_Measure_Count];
                }
                //else
                //{
                //    //从第三笔数据开始
                //    numPatternB.Value = numPatternG.Value = numPatternR.Value = Point_692AX[CAS200_Measure_Count + 2];
                //}
                Pattern_Write((byte)(numPatternR.Value), (byte)(numPatternG.Value), (byte)(numPatternB.Value));
                CAS200_Measure_Count++;
                Thread.Sleep(400);
                if (CAS200_Measure_Count > 23)
                {
                    T3.Enabled = false;
                    textBox1.Text += "绑点数据量测完毕\r\n";
                    //lumdataReadyFlag = true;
                    CAS200_Measure_Count = 0;
                }
                else
                {
                    btn_CAS200_Synt_Click(btn_CAS200_Measure_once, null);
                    T3.Enabled = true;
                }

            }

        }
        #endregion
        private void btn_CAS200_Synt_Click(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;

            switch (btnTmp.Name)
            {
                case "btn_CAS200_Measure_once":
                    {
                        Msr_CA310();
                        CAS200_Measure_Information(auto_lum, auto_x, auto_y);
                    }
                    break;
                case "btn_CAS200Save":
                    {
                        SaveFileDialog sf = new SaveFileDialog(); //对话框
                        sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义保存的文件的类型

                        string str = "序号,x坐标,y坐标,亮度\r\n";
                        if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                        {
                            if (sf.FileName == "") return; //如果没有输入文件名
                            try
                            {
                                StreamWriter sw = null; //文件流
                                sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                                for (int i = 0; i < (this.CAS200_dataGridView.Rows.Count - 1); i++)
                                {
                                    str = str + this.CAS200_dataGridView.Rows[i].Cells[0].Value.ToString() + ","
                                        + this.CAS200_dataGridView.Rows[i].Cells[1].Value.ToString() + ","
                                        + this.CAS200_dataGridView.Rows[i].Cells[2].Value.ToString() + ","
                                        + this.CAS200_dataGridView.Rows[i].Cells[3].Value.ToString() + "\r\n";

                                }
                                sw.WriteLine(str);
                                sw.Dispose(); //释放资源
                                sw.Close(); //关闭数据流
                                MessageBox.Show("CA310数据保存OK！", "系统提示：");
                            }
                            catch
                            {
                                MessageBox.Show("CA310数据保存时发生错误，请再试！", "系统提示：");
                            }
                        }
                    }
                    break;

                case "btn_CAS200_Clean":
                    {
                        DialogResult dr = MessageBox.Show("确认清空列表数据吗？", "系统提示", MessageBoxButtons.OKCancel);
                        if (dr == DialogResult.OK)
                        {
                            this.CAS200_dataGridView.Rows.Clear();
                        }
                        else {; }
                    }
                    break;
                case "btn_CAS200_Delect":
                    {
                        int Current_Index, Row_Accum;
                        Current_Index = this.CAS200_dataGridView.SelectedCells[0].RowIndex;
                        DataGridViewRow Row1 = CAS200_dataGridView.Rows[Current_Index];
                        this.CAS200_dataGridView.Rows.Remove(Row1);
                        this.CAS200_dataGridView.Rows[Current_Index].Selected = false;
                        Row_Accum = this.CAS200_dataGridView.Rows.Count - 1;
                        for (Current_Index = 0; Current_Index < Row_Accum; Current_Index++)
                        {
                            this.CAS200_dataGridView.Rows[Current_Index].Cells[0].Value = Current_Index + 1;//序号
                        }
                        this.CAS200_dataGridView.Rows[Row_Accum - 1].Selected = true;
                        CAS200_dataGridView.FirstDisplayedScrollingRowIndex = CAS200_dataGridView.RowCount - 1;
                    }
                    break;

                case "btn_CAS200_Stop":
                    {
                        T3.Enabled = false;
                    }
                    break;
                case "btn_CAS200_Start":
                    {
                        CAS200_Measure_Count = 0;
                        CAS200_Measure_Gray = 255;
                        //CA200_Measure_CE = byte.Parse((Convert.ToInt32(arr[arr.Length - 1], 16).ToString()));
                        T3.Enabled = true;
                        T3.Interval = int.Parse(CAS200_txt1.Text);//延时
                    }
                    break;
                default: break;
            }
        }
        CaSDK CaSDKObj = new CaSDK();
        private void btnCal_Click(object sender, EventArgs e)
        {
            gBx_CAS200_Auto_Test.Enabled = true;
            try
            {
                if (CA_Sel.SelectedIndex == 0)
                {
                    OLED_Show_Click(btnblack, e);
                    CaSDKObj.CA310_Connect();
                    CaSDKObj.CA310_Initial(byte.Parse(CA310_Channel.Text));
                }
                else if (CA_Sel.SelectedIndex == 1)
                {
                    OLED_Show_Click(btnblack, e);
                    CaSDKObj.AutoConnect();
                    CaSDKObj.SingleCalibration(0, byte.Parse(CA310_Channel.Text), double.Parse(CA410_Measure_Freq.Text));
                }
            }
            catch (Exception EX)
            {
                btnCal_manual.Enabled = true;
                MessageBox.Show("CA310/410 Connect Fail!!" + EX.Message);
            }
        }
        private void btnCal_manual_MouseEnter(object sender, EventArgs e)
        {
            ToolTip p = new ToolTip();
            p.ShowAlways = true;
            p.SetToolTip(this.btnCal_manual, "CA310连接校准，自带黑画面，按下静候6秒");
        }
        private void Msr_CA310()
        {
            try
            {

                if (CA_Sel.SelectedIndex == 0)
                {
                    MainForm.Msr_CASDK();
                    auto_lum = MainForm.CASDK_LUM;
                    auto_x = MainForm.CASDK_x;
                    auto_y = MainForm.CASDK_y;
                    //auto_T = CaSDKObj.objProbe.T;
                    //auto_duv = CaSDKObj.objProbe.duv;
                }
                else if (CA_Sel.SelectedIndex == 1)
                {
                    CaSDKObj.CA410_Measure_Lxy();
                    auto_lum = CaSDKObj.Lv;
                    auto_x = CaSDKObj.sx;
                    auto_y = CaSDKObj.sy;
                    /*
                    Ca410Obj.CA410_Measure_XYZ();
                    auto_frq = Ca410Obj.pVal;
                    lab_CASDK_Sf.Text= auto_frq.ToString().Substring(0, 6);
                    */
                }
            }
            catch
            {
                MessageBox.Show("请校准Senser！");
                //T17.Enabled = false;
                //return false;
            }
        }
        //浏览图片
        string path = "";
        private void btnBrowsePic_Click(object sender, EventArgs e)    //载入画面按键  选择文件夹
        {
            if (textBox2.Text != "")
            {
                MainForm.defaultfilePath = textBox2.Text;
            }
            else
            {
                StreamReader streamReader = new StreamReader("./update/Picaddr.txt", Encoding.Default);
                MainForm.defaultfilePath = streamReader.ReadLine();
                streamReader.Close();
            }
            FolderBrowserDialog fldb = new FolderBrowserDialog();
            //首次defaultfilePath为空，按FolderBrowserDialog默认设置（即桌面）选择            
            if (MainForm.defaultfilePath != "")
            {
                //设置此次默认目录为上一次选中目录
                fldb.SelectedPath = MainForm.defaultfilePath;
            }

            fldb.ShowNewFolderButton = false;
            DialogResult res = fldb.ShowDialog();
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("没选择任何文件夹.");
                return;
            }
            MainForm.defaultfilePath = fldb.SelectedPath;
            path = fldb.SelectedPath;
            if (!Directory.Exists(path))
            {
                MessageBox.Show("文件夹不存在.");
                return;
            }
            DirectoryInfo di = new DirectoryInfo(path);
            this.listBox3_BMPFile.Items.Clear();
            this.CreateListItem(di);//递归加载文件夹里的所有图片
            textBox2.Text = path;
            // -------------------------------------------------------------------------
            StreamWriter sw = null; //文件流
            sw = new StreamWriter("./update/Picaddr.txt", false, Encoding.Default);//Encoding.GetEncoding("UTF-8")
            sw.Write(MainForm.defaultfilePath);
            sw.Dispose(); //释放资源
            sw.Close(); //关闭数据流
        }
        /// <summary>
        /// 递归文件夹，把文件夹里所有后缀类似图片的文件，加入listbox
        /// </summary>
        /// <param name="di"></param>
        private void CreateListItem(DirectoryInfo di)
        {
            foreach (DirectoryInfo childDi in di.GetDirectories())
            {
                this.CreateListItem(childDi);
            }
            foreach (FileInfo fi in di.GetFiles())
            {
                if (ImageType.Contains(fi.Extension))//找到一个图片(如果用户手贱把一个excel文件后缀改成jpeg没办法)
                {
                    this.listBox3_BMPFile.Items.Add(new MyImage(fi.FullName));
                }
            }
        }
        private void lstImage_Click(object sender, EventArgs e)
        {
            if (listBox3_BMPFile.SelectedItem == null)
            {
                return;
            }
            MyImage selectedImg = (MyImage)listBox3_BMPFile.SelectedItem;
            Image img = new Bitmap(selectedImg.Path);
            pictureBox1.Image = img;
        }
        System.DateTime TimeNow2 = new DateTime();
        TimeSpan TimeCount2 = new TimeSpan();
        private void btnPrevPic_Click(object sender, EventArgs e)
        {
            Int32 HACT_True = 0;
            Int32 HACT_Skip = 0;
            Int32 VACT_True = 0;
            Int32 m_txlen = 0;
            Int32 j = 0;
            FileStream aFile;

            //byte[] TemFileContent = new byte[1024 * 100];
            byte[] TemFileContent = new byte[512 * 4000 + 100];
            System.Int32 ByteReaded = 0x00;

            string FileName = textBox2.Text + '\\' + listBox3_BMPFile.SelectedItem.ToString();
            aFile = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            ByteReaded = aFile.Read(TemFileContent, 0, 54);

            HACT_True = ((TemFileContent[19]) << 8) + TemFileContent[18];
            VACT_True = ((TemFileContent[23] << 8) + TemFileContent[22]);

            //   if (HACT.Value != HACT_True)
            //    {
            //          textBox1.Text += "图片宽度与设定不符\r\n";
            //         return;
            //     }
            /*
            if ((BridgeChipModel.SelectedIndex == 1) && (Dis_mode.SelectedIndex == 1)) //(Dis_mode.SelectedIndex == 1):MIPI 模式，因为下位机仅对MIPI模式做了优化
            {
                //------------20180903---------------
                try
                {   //bd 5a a5 9DF0-----提前下个标志位告诉下位机开始送图了，避免特殊图片格式导致错误配置
                    //BD A5 5A 9DF0-----提前下个标志位告诉下位机开始 快速 送图了
                    TemFileContent[0] = 0xbd; TemFileContent[1] = 0xa5; TemFileContent[2] = 0x5a; TemFileContent[3] = 0x9d; TemFileContent[4] = 0xf0;
                    comPort.Write(TemFileContent, 0, 5);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
                //-----------------------------------
                try
                {

                    j = 0;
                    int x, y, s = 0;
                    x = 512 * 4000; //单次传输数量
                    y = (VACT_True * HACT_True * 3 / x); //传输次数
                    if ((VACT_True * HACT_True * 3 % x) != 0)
                        y++;
                    {
                        //aFile.Seek(54, SeekOrigin.Begin);
                        while (j < y)
                        {
                            //if (HACT_True % 4 != 0)
                            //    aFile.Seek((VACT_True - j) * (HACT_True * 3 + (HACT_True % 4)) + 54, SeekOrigin.Begin);
                            //else
                            //    aFile.Seek((VACT_True - j) * HACT_True * 3 + 54, SeekOrigin.Begin);
                            aFile.Seek((j) * x + 54, SeekOrigin.Begin);

                            ByteReaded = aFile.Read(TemFileContent, 0, x);

                            try
                            {
                                comPort.Write(TemFileContent, 0, ByteReaded);
                            }
                            catch
                            {
                                MessageBox.Show("串口有误，请检查", "错误");
                                break;
                            }

                            progressBar1.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
                            label14.Text = progressBar1.Value.ToString() + "%";
                            Application.DoEvents();
                            j++;
                        }

                        TemFileContent[0] = 0x5A;
                        try
                        {
                            comPort.Write(TemFileContent, 0, 1);
                        }
                        catch
                        {
                            MessageBox.Show("串口有误，请检查", "错误");
                        }

                        aFile.Close();
                    }
                }
                catch
                {
                    MessageBox.Show("请选择文件夹", "错误");
                }
            }
            else*/
            {
                if ((MainForm.Dis_mode.SelectedIndex == 1) && (Pixel_Offset_Enable.Checked == true)) //video
                {
                    HACT_Skip = HACT_True % 10 > 0 ? (HACT_True + 10 - HACT_True % 10) : HACT_True;
                }
                else
                {
                    HACT_Skip = HACT_True;
                }
                try
                { //5a a5 9DF0731A-----提前下个标志位告诉下位机开始送图了，避免特殊图片格式导致错误配置
                    TemFileContent[0] = 0xbd; TemFileContent[1] = 0x5a; TemFileContent[2] = 0xa5; TemFileContent[3] = 0x9d; TemFileContent[4] = 0xf0;
                    MainForm.comPort.Write(TemFileContent, 0, 5);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
                //-----------------------------------
                try
                {
                    //HACT_True = Sig_mode.SelectedIndex > 2 ? Convert.ToInt32(2 * ((TemFileContent[19]<<8)+ TemFileContent[18])) : Convert.ToInt32((TemFileContent[19] << 8) + TemFileContent[18]);
                    j = 1;
                    while (j <= VACT_True)
                    {
                        //if (Sig_mode.SelectedIndex == 2)
                        //{
                        //    aFile.Seek((VACT_True - j) * HACT_True * 2 + 66, SeekOrigin.Begin);
                        //    ByteReaded = aFile.Read(TemFileContent, 0, HACT_True * 2);
                        //    try
                        //    {
                        //        MainForm.comPort.Write(TemFileContent, 0, HACT_Skip * 2);
                        //    }
                        //    catch
                        //    {
                        //        MessageBox.Show("串口有误，请检查", "错误");
                        //        break;
                        //    }
                        //    m_txlen += ByteReaded;
                        //    progressBar1.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
                        //    label14.Text = progressBar1.Value.ToString() + "%";
                        //    Application.DoEvents();//重点，必须加上，否则父子窗体都假死
                        //    j++;
                        //}
                        //else
                        {
                            if (HACT_True % 4 != 0)
                                aFile.Seek((VACT_True - j) * (HACT_True * 3 + (HACT_True % 4)) + 54, SeekOrigin.Begin);
                            else
                                aFile.Seek((VACT_True - j) * HACT_True * 3 + 54, SeekOrigin.Begin);

                            ByteReaded = aFile.Read(TemFileContent, 0, HACT_True * 3); // 
                            try
                            {
                                MainForm.comPort.Write(TemFileContent, 0, HACT_Skip * 3);
                            }
                            catch
                            {
                                MessageBox.Show("串口有误，请检查", "错误");
                                break;
                            }
                            m_txlen += ByteReaded;
                            progressBar1.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
                            label14.Text = progressBar1.Value.ToString() + "%";
                            Application.DoEvents();//重点，必须加上，否则父子窗体都假死
                            j++;
                        }
                    }

                    TemFileContent[0] = 0x5A;
                    try
                    {
                        MainForm.comPort.Write(TemFileContent, 0, 1);
                    }
                    catch
                    {
                        MessageBox.Show("串口有误，请检查", "错误");
                        return;
                    }
                    aFile.Close();
                }
                catch
                {
                    textBox1.Text += "啥图片都没显示";
                    textBox1.Select(textBox1.Text.Length, 0);
                    textBox1.ScrollToCaret();
                }
            }
        }
        public class MyImage
        {
            public MyImage(string p)
            {
                this.Path = p;
            }
            public string Path { get; set; }
            public override string ToString()
            {
                if (Path == null)
                {
                    return null;
                }
                return System.IO.Path.GetFileName(this.Path);
            }
        }
        #region //通用命令处理
        private void Send_Cmd_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            switch (btn.Name)
            {
                case "btnSend1":
                    {
                        MainForm.txtProcessDrivercode(txtCmd1.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend2":
                    {
                        MainForm.txtProcessDrivercode(txtCmd2.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend3":
                    {
                        MainForm.txtProcessDrivercode(txtCmd3.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;

            }
            Setting.TempRecord.cmdLen = 6;
            if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
            {
                MainForm.SendCmd(0);
            }
            else
            {
                MainForm.SendCmd(4);
            }
            textBox1.Text += "命令已下发...\r\n";
            textBox1.Select(textBox1.Text.Length, 0);
            textBox1.ScrollToCaret();
        }
        private void SaveCode_Click(object sender, EventArgs e)
        {
            SaveFileDialog txt = new SaveFileDialog();
            txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            string str = "//-----保存Driver IC Code文件------\r\n";
            if (txt.ShowDialog() == DialogResult.OK)
            {
                if (txt.FileName == " ")
                {
                    return;
                }
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(txt.FileName, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                try
                {
                    if (ChkCMD1.Checked)
                    {
                        str += "//---CMD1---\r\n" + txtCmd1.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    if (ChkCMD2.Checked)
                    {
                        str += "//---CMD2---\r\n" + txtCmd2.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    if (ChkCMD3.Checked)
                    {
                        str += "//---CMD3---\r\n" + txtCmd3.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("Driver IC Code保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("Driver IC Code保存时发生错误，请再试！", "系统提示：");
                }
            }
        }
        private void OpenTxtCode_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;

            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            of.Title = "初始化 Code";

            if (of.ShowDialog() == DialogResult.OK)
            {
                StreamReader streamReader = new StreamReader(of.FileName, Encoding.Default);
                switch (btn.Name)
                {
                    case "OpenTxtCode":
                        {
                            txtCmd1.Clear();
                            txtCmd1.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode2":
                        {
                            txtCmd2.Clear();
                            txtCmd2.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode3":
                        {
                            txtCmd3.Clear();
                            txtCmd3.Text = streamReader.ReadToEnd();
                        }
                        break;

                    default: break;
                }
                streamReader.Close();
            }
        }
        #endregion


        #region //------自定义功能按键---------------
        private void CustomSendCmd_Click(object sender, EventArgs e)   //自定义功能按键
        {
            Button btn = (Button)sender; string spedflag = "";
            switch (btn.Name)
            {
                case "btnFun1":
                    {
                        MainForm.txtProcessDrivercode(funcmd1, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag1;
                    }
                    break;
                case "btnFun2":
                    {
                        MainForm.txtProcessDrivercode(funcmd2, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag2;
                    }
                    break;
                case "btnFun3":
                    {
                        MainForm.txtProcessDrivercode(funcmd3, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag3;
                    }
                    break;
                case "btnFun4":
                    {
                        MainForm.txtProcessDrivercode(funcmd4, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag4;
                    }
                    break;
                case "btnFun5":
                    {
                        MainForm.txtProcessDrivercode(funcmd5, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag5;
                    }
                    break;
                case "btnFun6":
                    {
                        MainForm.txtProcessDrivercode(funcmd6, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag6;
                    }
                    break;
                case "btnFun7":
                    {
                        MainForm.txtProcessDrivercode(funcmd7, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag7;
                    }
                    break;
                case "btnFun8":
                    {
                        MainForm.txtProcessDrivercode(funcmd8, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag8;
                    }
                    break;

            }
            //Setting.TempRecord.cmdLen = 6;
            if (spedflag == "LP")
            {
                MainForm.SendCmd(0);  //低速
            }
            else
            {
                MainForm.SendCmd(4); //高速
            }
            textBox1.Text += "命令已下发...\r\n";
            textBox1.Select(textBox1.Text.Length, 0);
            textBox1.ScrollToCaret();
        }

        string FunDefaultfilePath = "";
        string funcmd1, funcmd2, funcmd3, funcmd4, funcmd5, funcmd6, funcmd7, funcmd8;
        //------------------------------------------------------------
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            path = Application.StartupPath + "\\x_ViewTrix";
            try
            {
                //StreamReader streamReader = new StreamReader(path+"\\Fun1.txt", Encoding.Default);
                //FunDefaultfilePath = streamReader.ReadLine();
                //streamReader.Close();
                ReadFuncfg(path + "\\Fun1.cfg", out String Ftitle1, out speedflag1, out funcmd1);
                btnFun1.Text = Ftitle1;

                ReadFuncfg(path + "\\Fun2.cfg", out String Ftitle2, out speedflag2, out funcmd2);
                btnFun2.Text = Ftitle2;

                ReadFuncfg(path + "\\Fun3.cfg", out String Ftitle3, out speedflag3, out funcmd3);
                btnFun3.Text = Ftitle3;

                ReadFuncfg(path + "\\Fun4.cfg", out String Ftitle4, out speedflag4, out funcmd4);
                btnFun4.Text = Ftitle4;

                ReadFuncfg(path + "\\Fun5.cfg", out String Ftitle5, out speedflag5, out funcmd5);
                btnFun5.Text = Ftitle5;

                ReadFuncfg(path + "\\Fun6.cfg", out String Ftitle6, out speedflag6, out funcmd6);
                btnFun6.Text = Ftitle6;

                ReadFuncfg(path + "\\Fun7.cfg", out String Ftitle7, out speedflag7, out funcmd7);
                btnFun7.Text = Ftitle7;

                ReadFuncfg(path + "\\Fun8.cfg", out String Ftitle8, out speedflag8, out funcmd8);
                btnFun8.Text = Ftitle8;
                //btnStore.Enabled = true;

                MessageBox.Show("向东说刷新完成", "～～～");
            }
            catch
            {
                MessageBox.Show("向东提示配置文件缺失，请检查", "错误");
            }
        }

        private void btnStore_Click(object sender, EventArgs e)
        {
            //FileStream fs = new FileStream(Application.StartupPath + "\\x_ViewTrix\\Fun1.txt", FileMode.Open)
            //SaveFileDialog txt = new SaveFileDialog();
            //txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            string str = "";
            //if (txt.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    StreamWriter sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_ViewTrix\\Fun1.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")

                    {
                        str += btnFun1.Text + "\r\n";//
                        str += speedflag1 + "\r\n";
                        str += funcmd1;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                                // MessageBox.Show("自定义命令保存OK，但请确认文件名是否规范！", "系统提示：");

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_ViewTrix\\Fun2.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")

                    {
                        str += btnFun2.Text + "\r\n";//
                        str += speedflag2 + "\r\n";
                        str += funcmd2;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_ViewTrix\\Fun3.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")

                    {
                        str += btnFun3.Text + "\r\n";//
                        str += speedflag3 + "\r\n";
                        str += funcmd3;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_ViewTrix\\Fun4.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")

                    {
                        str += btnFun4.Text + "\r\n";//
                        str += speedflag4 + "\r\n";
                        str += funcmd4;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_ViewTrix\\Fun5.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun5.Text + "\r\n";//
                        str += speedflag5 + "\r\n";
                        str += funcmd5;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_ViewTrix\\Fun6.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun6.Text + "\r\n";//
                        str += speedflag6 + "\r\n";
                        str += funcmd6;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_ViewTrix\\Fun7.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun7.Text + "\r\n";//
                        str += speedflag7 + "\r\n";
                        str += funcmd7;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_ViewTrix\\Fun8.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun8.Text + "\r\n";//
                        str += speedflag8 + "\r\n";
                        str += funcmd8;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    MessageBox.Show("向东说固化命令成功！", "系统提示：");
                    btnRefresh.Enabled = true;
                    btnStore.Enabled = false;
                }
                catch
                {
                    MessageBox.Show("固化命令时发生错误，请再试！", "系统提示：");
                }
            }
        }

        private void btnFunTestcmdSend_Click(object sender, EventArgs e)
        {
            String[] lines = txtFuncmd.Text.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            string speedflag = lines[1];
            String text = "";
            for (int i = 0; i < lines.Length; i++)
            {
                //假设删除第2行第3行
                if (i == 0 || i == 1)
                {
                    continue;
                }
                text += lines[i] + (i == lines.Length - 1 ? "" : "\r\n"); //最后一行不添加换行符
            }
            MainForm.txtProcessDrivercode(text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
            if (speedflag == "LP")
            {
                MainForm.SendCmd(0);  //低速
            }
            else
            {
                MainForm.SendCmd(4); //高速
            }
            textBox1.Text += "命令已下发...\r\n";
            textBox1.Select(textBox1.Text.Length, 0);
            textBox1.ScrollToCaret();
        }

        private void btnFunTestcmdSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog txt = new SaveFileDialog();
            txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            string str = "";
            if (txt.ShowDialog() == DialogResult.OK)
            {
                if (txt.FileName == " ")
                {
                    return;
                }
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(txt.FileName, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                try
                {

                    {
                        str += txtFuncmd.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n";
                    }

                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("自定义命令保存OK，但请确认文件名是否规范！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("保存时发生错误，请再试！", "系统提示：");
                }
            }
        }
        #region  //Gamma调整计时
        System.DateTime TimeNow = new DateTime();
        TimeSpan TimeCount = new TimeSpan();
        private void TimTest_Tick(object sender, EventArgs e)
        {
            TimeCount = DateTime.Now - TimeNow;
            txtTimeShow.Text = string.Format("{0:00}:{1:00}:{2:00}", TimeCount.Hours, TimeCount.Minutes, TimeCount.Seconds);
        }
        #endregion

        string speedflag1, speedflag2, speedflag3, speedflag4, speedflag5, speedflag6, speedflag7, speedflag8;

        private void btnFunLoad_Click(object sender, EventArgs e)
        {
            {
                StreamReader streamReader = new StreamReader("./update/Fun.cfg", Encoding.Default);
                FunDefaultfilePath = streamReader.ReadLine();
                streamReader.Close();
            }
            FolderBrowserDialog fldb = new FolderBrowserDialog();
            //首次defaultfilePath为空，按FolderBrowserDialog默认设置（即桌面）选择            
            if (FunDefaultfilePath != "")
            {
                //设置此次默认目录为上一次选中目录
                fldb.SelectedPath = FunDefaultfilePath;
            }

            fldb.ShowNewFolderButton = false;
            DialogResult res = fldb.ShowDialog();
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("没选择任何文件夹.");
                return;
            }
            FunDefaultfilePath = fldb.SelectedPath;
            path = fldb.SelectedPath;
            if (!Directory.Exists(path))
            {
                MessageBox.Show("文件夹不存在.");
                return;
            }
            //DirectoryInfo di = new DirectoryInfo(path);
            //this.listBox3_BMPFile.Items.Clear();
            //this.CreateListItem(di);//递归加载文件夹里的所有图片
            //textBox2.Text = path;            
            StreamWriter sw = null; //文件流
            sw = new StreamWriter("./update/Fun.cfg", false, Encoding.Default);//Encoding.GetEncoding("UTF-8")
            sw.Write(FunDefaultfilePath);
            sw.Dispose(); //释放资源
            sw.Close(); //关闭数据流
            // -------------------------------------------------------------------------
            try
            {
                //StreamReader streamReader = new StreamReader(path+"\\Fun1.txt", Encoding.Default);
                //FunDefaultfilePath = streamReader.ReadLine();
                //streamReader.Close();
                ReadFuncfg(path + "\\Fun1.txt", out String Ftitle1, out speedflag1, out funcmd1);
                btnFun1.Text = Ftitle1;

                ReadFuncfg(path + "\\Fun2.txt", out String Ftitle2, out speedflag2, out funcmd2);
                btnFun2.Text = Ftitle2;

                ReadFuncfg(path + "\\Fun3.txt", out String Ftitle3, out speedflag3, out funcmd3);
                btnFun3.Text = Ftitle3;

                ReadFuncfg(path + "\\Fun4.txt", out String Ftitle4, out speedflag4, out funcmd4);
                btnFun4.Text = Ftitle4;

                ReadFuncfg(path + "\\Fun5.txt", out String Ftitle5, out speedflag5, out funcmd5);
                btnFun5.Text = Ftitle5;

                ReadFuncfg(path + "\\Fun6.txt", out String Ftitle6, out speedflag6, out funcmd6);
                btnFun6.Text = Ftitle6;

                ReadFuncfg(path + "\\Fun7.txt", out String Ftitle7, out speedflag7, out funcmd7);
                btnFun7.Text = Ftitle7;

                ReadFuncfg(path + "\\Fun8.txt", out String Ftitle8, out speedflag8, out funcmd8);
                btnFun8.Text = Ftitle8;
                btnStore.Enabled = true;
            }
            catch
            {
                MessageBox.Show("向东提示配置文件缺失，请检查", "错误");
            }

        }
        private void ReadFuncfg(string addr, out String Ftitle, out String speedflag, out String Fcmd)
        {
            lines = new List<string>();

            //FileStream fs = new FileStream(Application.StartupPath + "\\x_ViewTrix\\Fun1.txt", FileMode.Open)
            FileStream fs = new FileStream(addr, FileMode.Open);
            StreamReader rd = new StreamReader(fs);
            string s;
            //读入文件所有行，存放到List<string>集合中
            while ((s = rd.ReadLine()) != null)
            {
                lines.Add(s);
            }
            rd.Close();
            fs.Close();
            //第一行在textBox1中显示
            Ftitle = "";
            speedflag = "";
            if (lines.Count > 0)
            {
                Ftitle = lines[0];
                speedflag = lines[1];
            }
            //txtFuncmd.Text = "";
            Fcmd = "";
            for (int i = 2; i < lines.Count; i++)
            {
                Fcmd += lines[i] + "\r\n";
            }

        }
        #endregion
        #region     //Gamma 调整
        private double[,] D_lums;//目标值-单色
        private double[] D_lum;//目标值-白色
        private double D_x, D_y;

        private int index = 0;
        private double lum_off, x_off, y_off;
        private double R_x = 0.67;//
        private double R_y = 0.33;
        private double G_x = 0.22;

        private double G_y = 0.71;
        private double B_x = 0.14;
        private double B_y = 0.06;
        private void btnSaveGamma_Click(object sender, EventArgs e)
        {
            SaveFileDialog txt = new SaveFileDialog();
            txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            string str = "//-----保存Gamma文件------\r\n";
            if (txt.ShowDialog() == DialogResult.OK)
            {
                if (txt.FileName == " ")
                {
                    return;
                }
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(txt.FileName, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                try
                {
                    {
                        str += txtGammadisplay.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n";
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("Gamma保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("保存时发生错误，请再试！", "系统提示：");
                }
            }
        }

        private void btnWriteGamma_Click(object sender, EventArgs e)
        {
            string tepcmd;
            if (txtCmd3.Text != "")
            {
                tepcmd = txtCmd3.Text;
                // GammaValueFormat_Click(GammaValueFormat, null);
                txtCmd3.Text = txtGammaCodeSample.Text + txtGammadisplay.Text + "\r\nC4,00";
                Send_Cmd_Click(btnSend3, null);
                txtCmd3.Text = tepcmd;
            }
            else
            {
                // GammaValueFormat_Click(GammaValueFormat, null);
                txtCmd3.Text = txtGammaCodeSample.Text + txtGammadisplay.Text + "\r\nC4,00";
                Send_Cmd_Click(btnSend3, null);
            }

        }
        private void btnLoadGamma_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;

            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            of.Title = "初始化 Code";

            if (of.ShowDialog() == DialogResult.OK)
            {
                StreamReader streamReader = new StreamReader(of.FileName, Encoding.Default);
                switch (btn.Name)
                {
                    case "btnLoadGamma":
                        {
                            txtGammadisplay.Clear();
                            txtGammadisplay.Text = streamReader.ReadToEnd();
                        }
                        break;

                    default: break;
                }
                streamReader.Close();
            }
        }

        private int[] Point_VTDR5120 = new int[25] {//---Gamma绑点数据，这里的数据仅供参考---
            0,1,3,5,7,11,15,19,23,27,31,35,39,47,55,63,71,79,95,111,127,159,191,223,255};

        private void btnCalGammaValue_Click(object sender, EventArgs e)
        {
            D_lum = new double[33]; //每阶目标亮度值
            //D_lums = new double[33, 3]; //填入亮度拆分后的RGB
            txtGammaPointsTargetValue.Text = "Gamma: \r\n";
            for (int i = 24; i != 0; i--)
            {
                D_lum[i] = (Math.Pow((Point_VTDR5120[i] / 255.0), Convert.ToDouble(txtVT_gamma.Text)) * Convert.ToDouble(txtVT_lum.Text));
                txtGammaPointsTargetValue.Text += "V" + Point_VTDR5120[i] + ":" + D_lum[i].ToString(("#0.0000")) + "\r\n";
            }
        }

        private uint[,] GammaValue = new uint[26, 3];//保存当前Gammavalue
        private void btnAdjReferenceGamma_Click(object sender, EventArgs e)
        {//设定Gamma参考基准,读取粘贴过来的Gamma文本，预处理后逐个填入GammaValue数组
            string strLine; string[] arr; uint m = 0;
            //1,清理文本框里面的注释等无用数据，并保存于DDICInitCmdarray;
            MainForm.txtProcessDrivercode(txtGammadisplay.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
            //2,对DDICInitCmdarray数据进行处理成合适的格式;
            for (int jt = 0; jt < MainForm.DDICInitCmdarray.Length / 3; jt++)
            {
                {
                    strLine = MainForm.DDICInitCmdarray[jt];
                    arr = strLine.Split(',');
                    for (int i = 0; i < (arr.Length - 1) / 2; i++)
                    {
                        GammaValue[m, 0] = (uint)((Convert.ToInt32(arr[2 * i + 1], 16) << 8) + (Convert.ToInt32(arr[2 * i + 2], 16) & 0xff));
                        m++;
                    }
                }
            }
            m = 0;
            for (int jt = 4; jt < 2 * MainForm.DDICInitCmdarray.Length / 3; jt++)
            {
                {
                    strLine = MainForm.DDICInitCmdarray[jt];
                    arr = strLine.Split(',');
                    for (int i = 0; i < (arr.Length - 1) / 2; i++)
                    {
                        GammaValue[m, 1] = (uint)((Convert.ToInt32(arr[2 * i + 1], 16) << 8) + (Convert.ToInt32(arr[2 * i + 2], 16) & 0xff));
                        m++;
                    }
                }
            }
            m = 0;
            for (int jt = 8; jt < MainForm.DDICInitCmdarray.Length; jt++)
            {
                {
                    strLine = MainForm.DDICInitCmdarray[jt];
                    arr = strLine.Split(',');
                    for (int i = 0; i < (arr.Length - 1) / 2; i++)
                    {
                        GammaValue[m, 2] = (uint)((Convert.ToInt32(arr[2 * i + 1], 16) << 8) + (Convert.ToInt32(arr[2 * i + 2], 16) & 0xff));
                        m++;
                    }
                }
            }
        }
        static byte[] GetCRCArray(byte[] arr, Byte speedflag)
        {
            CRC16 CRCData = new CRC16();

            int arrNumbuer;                                                                                                                                                                                                                                                                                                                                             //51
            arrNumbuer = arr.Length;
            arrNumbuer += 6;
            byte[] Send_Datax = new byte[arrNumbuer];
            Send_Datax[0] = 0x9f;
            Send_Datax[1] = (byte)(speedflag << 4);
            Send_Datax[2] = Convert.ToByte(arr.Length + 1);  //为兼容下位机命令，此位置填待传输有效数据长度+1 

            Send_Datax[arr.Length + 3] = 0xFF;  //添加结束标志位
            arr.CopyTo(Send_Datax, 3);//合并数组头 4个Byte 标志位
            //计算校验码                                                 
            CRCData.CalculateCrc16(Send_Datax, out Send_Datax[arrNumbuer - 2], out Send_Datax[arrNumbuer - 1]);
            return Send_Datax;
        }
        byte[] GammaValueTeparr = new byte[54 * 3]; //存放格式化后的GammaValue，以便于直接下发至DDIC
        private void GammaValueFormat_Click(object sender, EventArgs e)
        {
            txtGammadisplay.Text = "B0"; //Convert.ToString(要转的数,16);
            for (int i = 0; i < 8; i++)
            {
                txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);
                GammaValueTeparr[0] = 0xb0;
                GammaValueTeparr[2 * i + 1] = (byte)(GammaValue[i, 0] >> 8);
                GammaValueTeparr[2 * i + 2] = (byte)(GammaValue[i, 0] & 0xff);
            }
            txtGammadisplay.Text += "\r\n" + "B1"; //Convert.ToString(要转的数,16);
            for (int i = 8; i < 16; i++)
            {
                txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);
                GammaValueTeparr[0 + 17] = 0xb1;
                GammaValueTeparr[2 * i + 2] = (byte)(GammaValue[i, 0] >> 8);
                GammaValueTeparr[2 * i + 3] = (byte)(GammaValue[i, 0] & 0xff);
            }
            txtGammadisplay.Text += "\r\n" + "B2"; //Convert.ToString(要转的数,16);
            for (int i = 16; i < 24; i++)
            {
                txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);
                GammaValueTeparr[0 + 34] = 0xb2;
                GammaValueTeparr[2 * i + 3] = (byte)(GammaValue[i, 0] >> 8);
                GammaValueTeparr[2 * i + 4] = (byte)(GammaValue[i, 0] & 0xff);
            }
            txtGammadisplay.Text += "\r\n" + "B3"; //Convert.ToString(要转的数,16);
            for (int i = 24; i < 25; i++)
            {
                txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 0] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 0] & 0xff, 16);
                GammaValueTeparr[0 + 51] = 0xb3;
                GammaValueTeparr[2 * i + 4] = (byte)(GammaValue[i, 0] >> 8);
                GammaValueTeparr[2 * i + 5] = (byte)(GammaValue[i, 0] & 0xff);
            }
            //-------------
            txtGammadisplay.Text += "\r\n" + "B4"; //Convert.ToString(要转的数,16);
            for (int i = 0; i < 8; i++)
            {
                txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 1] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 1] & 0xff, 16);
                GammaValueTeparr[54 + 0] = 0xb4;
                GammaValueTeparr[54 + 2 * i + 1] = (byte)(GammaValue[i, 1] >> 8);
                GammaValueTeparr[54 + 2 * i + 2] = (byte)(GammaValue[i, 1] & 0xff);
            }
            txtGammadisplay.Text += "\r\n" + "B5"; //Convert.ToString(要转的数,16);
            for (int i = 8; i < 16; i++)
            {
                txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 1] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 1] & 0xff, 16);
                GammaValueTeparr[54 + 0 + 17] = 0xb5;
                GammaValueTeparr[54 + 2 * i + 2] = (byte)(GammaValue[i, 1] >> 8);
                GammaValueTeparr[54 + 2 * i + 3] = (byte)(GammaValue[i, 1] & 0xff);
            }
            txtGammadisplay.Text += "\r\n" + "B6"; //Convert.ToString(要转的数,16);
            for (int i = 16; i < 24; i++)
            {
                txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 1] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 1] & 0xff, 16);
                GammaValueTeparr[54 + 0 + 34] = 0xb6;
                GammaValueTeparr[54 + 2 * i + 3] = (byte)(GammaValue[i, 1] >> 8);
                GammaValueTeparr[54 + 2 * i + 4] = (byte)(GammaValue[i, 1] & 0xff);
            }
            txtGammadisplay.Text += "\r\n" + "B7"; //Convert.ToString(要转的数,16);
            for (int i = 24; i < 25; i++)
            {
                txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 1] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 1] & 0xff, 16);
                GammaValueTeparr[54 + 0 + 51] = 0xb7;
                GammaValueTeparr[54 + 2 * i + 4] = (byte)(GammaValue[i, 1] >> 8);
                GammaValueTeparr[54 + 2 * i + 5] = (byte)(GammaValue[i, 1] & 0xff);
            }

            txtGammadisplay.Text += "\r\n" + "B8"; //Convert.ToString(要转的数,16);
            for (int i = 0; i < 8; i++)
            {
                txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 2] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 2] & 0xff, 16);
                GammaValueTeparr[108 + 0 + 0] = 0xb8;
                GammaValueTeparr[108 + 2 * i + 1] = (byte)(GammaValue[i, 2] >> 8);
                GammaValueTeparr[108 + 2 * i + 2] = (byte)(GammaValue[i, 2] & 0xff);
            }
            txtGammadisplay.Text += "\r\n" + "B9"; //Convert.ToString(要转的数,16);
            for (int i = 8; i < 16; i++)
            {
                txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 2] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 2] & 0xff, 16);
                GammaValueTeparr[108 + 0 + 17] = 0xb9;
                GammaValueTeparr[108 + 2 * i + 2] = (byte)(GammaValue[i, 2] >> 8);
                GammaValueTeparr[108 + 2 * i + 3] = (byte)(GammaValue[i, 2] & 0xff);
            }
            txtGammadisplay.Text += "\r\n" + "BA"; //Convert.ToString(要转的数,16);
            for (int i = 16; i < 24; i++)
            {
                txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 2] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 2] & 0xff, 16);
                GammaValueTeparr[108 + 0 + 34] = 0xba;
                GammaValueTeparr[108 + 2 * i + 3] = (byte)(GammaValue[i, 2] >> 8);
                GammaValueTeparr[108 + 2 * i + 4] = (byte)(GammaValue[i, 2] & 0xff);
            }
            txtGammadisplay.Text += "\r\n" + "BB"; //Convert.ToString(要转的数,16);
            for (int i = 24; i < 25; i++)
            {
                txtGammadisplay.Text += "," + Convert.ToString(GammaValue[i, 2] >> 8, 16) + "," + Convert.ToString(GammaValue[i, 2] & 0xff, 16);
                GammaValueTeparr[108 + 0 + 51] = 0xbb;
                GammaValueTeparr[108 + 2 * i + 4] = (byte)(GammaValue[i, 2] >> 8);
                GammaValueTeparr[108 + 2 * i + 5] = (byte)(GammaValue[i, 2] & 0xff);
            }
        }
        private void GammaValueSet(byte rh, byte rl, byte gh, byte gl, byte bh, byte bl, byte[] Gammaarr)
        {   //通过高速方式向第一条Gamma写入一组Gamma值
            byte[] TepArr;
            try
            {
                TepArr = new byte[] { 3, 0xf0, 0xaa, 0x13,
                    4, 0XFF, 0XFF, 0XFF, 25,
                    2, 0xbf, 0x01,   //第一条Gamma
                    4, 0XFF, 0XFF, 0XFF, 25,
                    2, 0xc4, 0x01,
                    4, 0XFF, 0XFF, 0XFF, 25 };  //byte[] TepArr;
                MainForm.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);
                //-----------------  
                TepArr = new byte[] {
                17,0xB0, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                17,0xB1, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                17,0xB2, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                3, 0xB3, 00, 00,
                17,0xB4, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                17,0xB5, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                17,0xB6, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                3, 0xB7, 03, 00,
                17,0xB8, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                17,0xB9, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                17,0xBa, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 ,
                3, 0xBb, 00, 00,
                2,0xc4, 0x00
                };

                Array.Copy(Gammaarr, 0, TepArr, 1, 17);
                Array.Copy(Gammaarr, 17, TepArr, 1 + 18 * 1, 17);
                Array.Copy(Gammaarr, 34, TepArr, 1 + 18 * 2, 17);
                Array.Copy(Gammaarr, 51, TepArr, 1 + 18 * 3, 3);

                Array.Copy(Gammaarr, 54, TepArr, 1 + 18 * 3 + 4, 17);
                Array.Copy(Gammaarr, 71, TepArr, 1 + 18 * 4 + 4, 17);
                Array.Copy(Gammaarr, 88, TepArr, 1 + 18 * 5 + 4, 17);
                Array.Copy(Gammaarr, 105, TepArr, 1 + 18 * 6 + 4, 3);

                Array.Copy(Gammaarr, 108, TepArr, 1 + 18 * 6 + 8, 17);
                Array.Copy(Gammaarr, 125, TepArr, 1 + 18 * 7 + 8, 17);
                Array.Copy(Gammaarr, 142, TepArr, 1 + 18 * 8 + 8, 17);
                Array.Copy(Gammaarr, 159, TepArr, 1 + 18 * 9 + 8, 3);
                //public static void Copy(
                //Array sourceArray,
                //int sourceIndex,
                //Array destinationArray,
                //int destinationIndex,
                //int length); 
                MainForm.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾
                //Application.DoEvents();//重点，必须加上，否则父子窗体都假死
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
        }
        private void btnAutoGammas_VTDR6100_Click(object sender, EventArgs e)
        {
            int flag = 1;
            double Lr_d, Lg_d, Lb_d;
            D_lums = new double[25, 3];
            D_lum = new double[25];
            index = 2;  //末尾绑点不调算了

            TimTest.Start();
            TimeNow = DateTime.Now; //开始计时

            for (int i = 0; i < 25; i++)
            {
                D_lum[i] = (Math.Pow((Point_VTDR5120[i] / 255.0), Convert.ToDouble(txtVT_gamma.Text)) * Convert.ToDouble(txtVT_lum.Text));
            }

            D_x = Convert.ToDouble(txtVT_x.Text);
            D_y = Convert.ToDouble(txtVT_y.Text);
            Lr_d = R_y * ((D_y - G_y) * (B_x - D_x) + (D_x - G_x) * (D_y - B_y)) / B_y / ((D_y - G_y) * (D_x - R_x) + (D_x - G_x) * (R_y - D_y));
            Lb_d = 1.0;
            Lg_d = G_y * ((D_y - R_y) * (B_x - D_x) + (D_x - R_x) * (D_y - B_y)) / B_y / ((D_y - R_y) * (D_x - G_x) + (D_x - R_x) * (G_y - D_y));

            for (int i = 0; i < 25; i++)
            {
                D_lums[i, 0] = D_lum[i] * Lr_d / (Lr_d + Lg_d + Lb_d);
                D_lums[i, 1] = D_lum[i] * Lg_d / (Lr_d + Lg_d + Lb_d);
                D_lums[i, 2] = D_lum[i] * Lb_d / (Lr_d + Lg_d + Lb_d);
            }

            switch (flag)
            {
                case 1://寄存器值与亮度正比
                    {
                        //lum_off = Convert.ToDouble(txtVT_loff.Text);
                        x_off = Convert.ToDouble(txtVT_xoff.Text);
                        y_off = Convert.ToDouble(txtVT_yoff.Text);
                        OLED_Show_Click(btnwhite, e);
                        ReceivOKFlag = false;
                        T17.Enabled = true;
                    }
                    break;
                case 2:  //寄存器值与亮度反比
                    break;
                default:
                    break;
            }
        }
        private void T17_Tick(object sender, EventArgs e)
        {
            double Lr_t, Lg_t, Lb_t, lumr, lumg, lumb;
            T17.Enabled = false;
            T17.Interval = 200;
            if (!ReceivOKFlag)
            {
                numPatternR.Value = Point_VTDR5120[26 - index];
                numPatternG.Value = Point_VTDR5120[26 - index];
                numPatternB.Value = Point_VTDR5120[26 - index];
                OLED_Show_Click(btnPatternW, e);//写入Pattern参数
            }
            Msr_CA310();

            txtlvshow.Text = "Lv: " + auto_lum + "\r\n" + "x: " + auto_x + "\r\n" + "y: " + auto_y + "\r\n";
            if (index > 2)
                labTargetlum.Text = "Tar:" + D_lum[26 - index];

            Lr_t = R_y * ((auto_y - G_y) * (B_x - auto_x) + (auto_x - G_x) * (auto_y - B_y)) / B_y / ((auto_y - G_y) * (auto_x - R_x) + (auto_x - G_x) * (R_y - auto_y));
            Lb_t = 1.0;
            Lg_t = G_y * ((auto_y - R_y) * (B_x - auto_x) + (auto_x - R_x) * (auto_y - B_y)) / B_y / ((auto_y - R_y) * (auto_x - G_x) + (auto_x - R_x) * (G_y - auto_y));
            lumr = auto_lum * Lr_t / (Lr_t + Lg_t + Lb_t);
            lumg = auto_lum * Lg_t / (Lr_t + Lg_t + Lb_t);
            lumb = auto_lum * Lb_t / (Lr_t + Lg_t + Lb_t);

            lum_off = (D_lum[26 - index] * Convert.ToDouble(numVT_loff.Value) / 1000);
            x_off = Convert.ToDouble(txtVT_xoff.Text);
            y_off = Convert.ToDouble(txtVT_yoff.Text);

            if ((auto_lum < (D_lum[26 - index] + lum_off)) && (auto_lum > (D_lum[26 - index] - lum_off)))//
                flag1 = 0;
            if ((auto_y < (D_y + y_off)) && (auto_y > (D_y - y_off)) && flag1 == 0)//
                flag2 = 0;
            if ((auto_x < (D_x + x_off)) && (auto_x > (D_x - x_off)) && flag1 == 0)//
                flag3 = 0;

            if (flag1 == 0 && flag2 == 0 && flag3 == 0)
            {
                T17.Enabled = false;
                index++;

                if (index == 25)
                {
                    TimTest.Stop();//停止计时
                    textBox1.Text = textBox1.Text + "VTDR6100 gamma调试完毕!\r\n";
                    textBox1.Focus();//获取焦点
                    textBox1.Select(textBox1.TextLength, 0);//光标定位到文本最后
                    textBox1.ScrollToCaret();//滚动到光标处
                    //FirstAdjGammaFlag = true;
                    return;
                }
                if (index < 26)
                {
                    textBox1.Text += index + "" + "完成...";
                    textBox1.Select(textBox1.Text.Length, 0);
                    textBox1.ScrollToCaret();

                    txtGammadisplay.Text = "";
                    for (int i = 0; i < 25; i++)
                    {
                        //Convert.ToString(要转的数, 16);//string s = string.Format("0x{0:X2}", i);    // s = 0x0F;
                        txtGammadisplay.Text += (i + 1) + ",R/G/B, V" + Point_VTDR5120[24 - i] + ": " + string.Format("0x{0:X2}", GammaValue[24 - i, 0]) + "--";
                        txtGammadisplay.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 1]) + "--";
                        txtGammadisplay.Text += string.Format("0x{0:X2}", GammaValue[24 - i, 2]) + "\r\n";
                    }

                    Thread.Sleep(10); //1秒=1000毫秒，
                    //T17.Enabled = true;
                    flag1 = 1;
                    flag2 = 1;
                    flag3 = 1;
                }

                numPatternR.Value = Point_VTDR5120[26 - index];
                numPatternG.Value = Point_VTDR5120[26 - index];
                numPatternB.Value = Point_VTDR5120[26 - index];
                OLED_Show_Click(btnPatternW, e);//写入Pattern参数
                ReceivOKFlag = false;
                Thread.Sleep(100);
                T17.Enabled = true;
            }
            else
            {
                //Lr_t = R_y * ((auto_y - G_y) * (B_x - auto_x) + (auto_x - G_x) * (auto_y - B_y)) / B_y / ((auto_y - G_y) * (auto_x - R_x) + (auto_x - G_x) * (R_y - auto_y));
                //Lb_t = 1.0;
                //Lg_t = G_y * ((auto_y - R_y) * (B_x - auto_x) + (auto_x - R_x) * (auto_y - B_y)) / B_y / ((auto_y - R_y) * (auto_x - G_x) + (auto_x - R_x) * (G_y - auto_y));
                //lumr = auto_lum * Lr_t / (Lr_t + Lg_t + Lb_t);
                //lumg = auto_lum * Lg_t / (Lr_t + Lg_t + Lb_t);
                //lumb = auto_lum * Lb_t / (Lr_t + Lg_t + Lb_t);

                //try
                {
                    step_l = (byte)(int.Parse(numStep.Value.ToString()));

                    switch (index)
                    {
                        case 0:
                        case 1:
                            {
                                GammaValue[0, 1] = 0;  //0绑点不调，直接送零
                                GammaValue[0, 2] = 0;
                                GammaValue[0, 0] = 0;
                                GammaValue[1, 1] = 0;  //1绑点不调，直接送零
                                GammaValue[1, 2] = 0;
                                GammaValue[1, 0] = 0;

                                index++;
                            }
                            break;

                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                        case 12:
                        case 13:
                        case 14:
                        case 15:
                        case 16:
                        case 17:
                        case 18:
                        case 19:
                        case 20:
                        case 21:
                        case 22:
                        case 23:
                        case 24:
                            {
                                if ((flag3 == 1) | (flag2 == 1) | (flag1 == 1))
                                {

                                    {
                                        if (lumr > D_lums[26 - index, 0])
                                            GammaValue[26 - index, 0] = GammaValue[26 - index, 0] - (byte)(int.Parse(numStep.Value.ToString()));
                                        else GammaValue[26 - index, 0] = GammaValue[26 - index, 0] + step_l;
                                        /*if (VTDR6100_R127.Value <= VTDR6100_R111.Value)
                                            VTDR6100_R127.Value = VTDR6100_R111.Value + step_h;*/
                                    }

                                    //}
                                    //if (flag1 == 1)
                                    {

                                        {
                                            if (lumg > D_lums[26 - index, 1])
                                                GammaValue[26 - index, 1] = GammaValue[26 - index, 1] - step_l;
                                            else GammaValue[26 - index, 1] = GammaValue[26 - index, 1] + step_l;
                                            /*if (VTDR6100_G127.Value <= VTDR6100_G111.Value)
                                                VTDR6100_G127.Value = VTDR6100_G111.Value + step_h;*/
                                        }
                                        //adjust_Gnum++;
                                    }
                                    //if (flag2 == 1)
                                    //{

                                    {
                                        if (lumb > D_lums[26 - index, 2])
                                            GammaValue[26 - index, 2] = GammaValue[26 - index, 2] - step_l;
                                        else GammaValue[26 - index, 2] = GammaValue[26 - index, 2] + step_l;
                                        /*if (VTDR6100_B127.Value <= VTDR6100_B111.Value)
                                            VTDR6100_B127.Value = VTDR6100_B111.Value + step_h;*/
                                    }

                                }

                                for (int i = 24; i > 1; i--)
                                {
                                    if (GammaValue[i, 0] < GammaValue[i - 1, 0])
                                    {
                                        GammaValue[i - 1, 0] = GammaValue[i, 0] - 0;
                                        //GammaValueFormat_Click(null, null);
                                    }
                                    if (GammaValue[i, 1] < GammaValue[i - 1, 1])
                                    {
                                        GammaValue[i - 1, 1] = GammaValue[i, 1] - 0;
                                        //GammaValueFormat_Click(null, null);
                                    }
                                    if (GammaValue[i, 2] < GammaValue[i - 1, 2])
                                    {
                                        GammaValue[i - 1, 2] = GammaValue[i, 2] - 0;
                                        //GammaValueFormat_Click(null, null);
                                    }

                                }

                                GammaValueFormat_Click(null, null);

                                byte rh = (Byte)(GammaValue[26 - index, 0] >> 8);
                                byte rl = (Byte)(GammaValue[26 - index, 0] & 0xff);
                                byte gh = (Byte)(GammaValue[26 - index, 1] >> 8);
                                byte gl = (Byte)(GammaValue[26 - index, 1] & 0xff);
                                byte bh = (Byte)(GammaValue[26 - index, 2] >> 8);
                                byte bl = (Byte)(GammaValue[26 - index, 2] & 0xff);
                                txtGammaValue.Text = GammaValue[26 - index, 0] + "\r\n" + GammaValue[26 - index, 1] + "\r\n" + GammaValue[26 - index, 2] + "\r\n";
                                GammaValueSet(rh, rl, gh, gl, bh, bl, GammaValueTeparr);
                                Thread.Sleep(100);
                                Application.DoEvents();//重点，必须加上，否则父子窗体都假死
                                //SendGamma2VTDR();
                                //Thread.Sleep(100);
                            }
                            break;
                        case 25:
                            {
                                //for (int k = 0; k < 13; k++)
                                //{
                                //    numPatternR.Value = Parttern_VTDR6100[k];
                                //    numPatternG.Value = Parttern_VTDR6100[k];
                                //    numPatternB.Value = Parttern_VTDR6100[k];
                                //    OLED_Show_Click(btnPatternW, e);//写入Pattern参数
                                //    Thread.Sleep(1000); //1秒=1000毫秒，
                                //    Msr_CA310();
                                //    CAS200_Measure_Information(auto_lum, auto_x, auto_y);
                                //}
                                T17.Enabled = false;
                            }
                            break;

                        default:
                            T17.Enabled = false;
                            break;
                    }
                    System.Threading.Thread.Sleep(10);
                }
                //catch
                //{
                //    T5.Enabled = false;
                //    MessageBox.Show("数值超限！");
                //    return;
                // }
                T17.Enabled = true;
            }

        }
        private void btnVTStop_Click(object sender, EventArgs e)
        {
            T17.Enabled = false;
            flag1 = 1;
            flag2 = 1;
            flag3 = 1;
        }
        #endregion
    }
}
